package com.cgnpc.scp.filter;

import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.scp.common.utils.AjaxResultUtil;
import com.cgnpc.scp.common.utils.IOUtil;
import com.cgnpc.scp.common.utils.JacksonUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

@Component
@WebFilter(filterName = "CharSafeWithSqlFilter", urlPatterns = "/scp/psc/*")
public class CharSafeWithSqlFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(CharSafeWithSqlFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            LOGGER.info("request url:{}",((HttpServletRequest)request).getRequestURI());
            // && !"/scp/agent/adapter/outer".equals(((HttpServletRequest)request).getRequestURI())
            if (request instanceof HttpServletRequest) {
                boolean onlyCheckUnsafeChar = true;
                CharSafeRequestWrapper charSafeRequestWrapper = new CharSafeRequestWrapper((HttpServletRequest) request, onlyCheckUnsafeChar);

                if (charSafeRequestWrapper.hasUnsafeChar()) {
                    ServletOutputStream servletOutputStream = null;
                    PrintWriter writer = null;

                    try {
                        servletOutputStream = response.getOutputStream();
                        writer = new PrintWriter(new OutputStreamWriter(servletOutputStream, StringUtil.CHARSET_UTF8));

                        AjaxResult ajaxResult = AjaxResultUtil.createErrorMessage("请求信息包含不安全的字符，请求已经结束");
                        writer.print(JacksonUtil.writeValueAsString(ajaxResult));
                        writer.flush();
                    } catch (Exception e) {
                        LOGGER.error("servletOutputStream.error;", e);
                    } finally {
                        IOUtil.close(servletOutputStream);
                        IOUtil.close(writer);
                    }

                    return;
                }

                chain.doFilter(charSafeRequestWrapper, response);
            } else {
                chain.doFilter(request, response);
            }
        } catch (Exception e) {
            LOGGER.error("error", e);
            throw e;
        }
    }

    @Override
    public void destroy() {

    }
}
